// websocket.js  
import { mapMutations, mapState } from 'vuex'

	
class WebSocketManager {  
    constructor(userId, userInfo) {  
		this.userId = userId;  
		this.userInfo = userInfo; // 假设这是用户信息，包括nickName等  
		this.wsTaskId = null;  
		this.messages = []; // 用于存储接收到的消息  
		this.initWebSocket();  
	} 
  
    initWebSocket() {  
        const wsUrl = uni.$http.wsUrl +`${this.userId}`;  
        this.wsTaskId = uni.connectSocket({  
            url: wsUrl,  
            success: () => {  
                console.log('尝试连接 WebSocket');  
            },  
            fail: (err) => {  
                console.error('WebSocket 连接失败:', err);  
            }  
        });  
  
        uni.onSocketOpen((res) => {  
            console.log('WebSocket 连接已打开', res);  
            // 这里可以调用其他方法或处理逻辑  
        });  
  
        // 可以添加其他事件监听，如接收消息、关闭等  
        uni.onSocketMessage((res) => {  
			if(res.data==""){
				  return;
			  }
			  var jsonObj = JSON.parse(res.data);
			  if(jsonObj.myId!=this.sellerId){
				  return;
			  }
			  let obj = {
					botContent: jsonObj.message,
					userContent: "",
					image:"/static/uni.png",
					time: jsonObj.time,
			  }
			  
			this.getLastMessage(jsonObj.toId,jsonObj.myId,jsonObj.time,jsonObj.message)
			this.msgList.push(obj);
			console.log('收到 WebSocket 消息:', res.data);
        });  
  
        uni.onSocketError((err) => {  
            console.error('WebSocket 发生错误：', err);  
        });  
  
        uni.onSocketClose((res) => {  
            console.log('WebSocket 连接已关闭', res);  
        });  
    }  
  
   
	
	 //最后一个消息
	/* getLastMessage(myId,toId,time,message,messageObj){
	   //获取到当前消息，然后放到消息list中
		this.messageObj.myId=myId;
		this.messageObj.toId=toId;
		this.messageObj.time= time;
		this.messageObj.lastMessage=message;
		this.messageObj.myName=this.userinfo.nickName;
		this.messageList = this.messagelist.filter(item => (item[myId] === myId && item[toId] === toId));
	   this.messageList.push(this.messageObj);
	   //this.updatMessagelistInfo(this.messageList)
	  } */
}  
  
// 导出WebSocketManager类  
export default WebSocketManager;